package servlet;

import dao.Db;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/showlist")
public class ShowList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受用户请求，访问业务逻辑层，获取表中所有数据，并且渲染成表格
        // .设置响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //接受请求
        PrintWriter writer = resp.getWriter();

        Db db = new Db();
        List<User> allData = db.getAllData();
        System.out.println(allData);

        writer.write("<!DOCTYPE html>");
        writer.write("<html>");
        writer.write("<head><title>用户信息</title><meta charset='utf-8'></head>");
        writer.write("<body style='background:lightgreen;'>");
        writer.write("<table border='1'cellpadding='1'width='800'align='center'cellspcing='1'>");
        writer.write("<tr><th>用户id</th><th>用户姓名</th><th>密码</th><th>生日</th><th>操作1</th><th>操作2</th></tr>");
        for (int i = 0; i <allData.size(); i++) {
            writer.write("<tr><td>" + allData.get(i).getId() + "</td>");
            writer.write("<td>" + allData.get(i).getUsername() + "</td>");
            writer.write("<td>" +allData.get(i).getPassword() + "</td>");
            writer.write("<td>" +allData.get(i).getBirthday() + "</td>");
            writer.write("<td><a href=\"/javaWebStudy2025_war_exploded/my.do?method=delDo&id="+allData.get(i).getId()+"\"onclick=\"if(confirm('确定么？'))return true;return false;\">删除</a></td>");
            writer.write("<td><a href=/javaWebStudy2025_war_exploded/update?id=" + allData.get(i).getId() + ">更新</a></td></tr>");
        }
        writer.write("</table>");
        writer.write("</body>");
        writer.write("</html>");
    }
}
